package com.wangcanxuan.www.service.Impl;

import com.wangcanxuan.www.annotation.Transaction;
import com.wangcanxuan.www.dao.mapper.*;
import com.wangcanxuan.www.entity.dto.ResultInfo;
import com.wangcanxuan.www.entity.po.*;
import com.wangcanxuan.www.exception.ServiceException;
import com.wangcanxuan.www.proxy.DaoProxy;
import com.wangcanxuan.www.service.TribeService;
import com.wangcanxuan.www.util.SecurityUtil;
import com.wangcanxuan.www.util.ValidateUtil;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

import static com.wangcanxuan.www.entity.dto.ResultConstants.SUCCESS_REQUEST_CODE;
import static com.wangcanxuan.www.service.constant.ServiceConstants.*;


/**
 * 部落业务实现类
 *
 * @author HHLJ
 * @date 2022/03/27
 */
public class TribeServiceImpl implements TribeService {

    private final UserMapper USER_MAPPER = DaoProxy.getMapper(UserMapper.class);
    private final TribeMapper TRIBE_MAPPER = DaoProxy.getMapper(TribeMapper.class);
    private final ApplyMapper APPLY_MAPPER = DaoProxy.getMapper(ApplyMapper.class);
    private final RoleMapper ROLE_MAPPER = DaoProxy.getMapper(RoleMapper.class);


    @Override
    public ResultInfo<String> createTribe(User user, String tribeName) {
        // 判断该用户是否加入部落
        if (!ValidateUtil.strIsNullOrEmpty(user.getTribeId())) {
            return ResultInfo.operateRejectWithMessage("已加入部落,无法创建部落!");
        }

        // 判断该用户的金币是否足够
        if (user.getCoins() < CREATE_COINS) {
            return ResultInfo.operateRejectWithMessage("小老弟，钱都不够建嘛呢部落！");
        }

        // 通过阵营和部落名在数据库中查询
        Tribe tribe = new Tribe();
        tribe.setCamp(user.getCamp());
        tribe.setTribeName(tribeName);
        tribe = TRIBE_MAPPER.selectOneByFields(tribe);

        // 判断数据库中是否已经有了同样部落名的部落
        if (tribe != null) {
            return ResultInfo.operateRejectWithMessage("该部落名已存在!");
        }

        // 创建uuid主键
        String id = SecurityUtil.uuidCreateId();

        // 创建插入到数据库中的部落对象
        Tribe insertTribe = new Tribe(id, user.getCamp(), tribeName, user.getNickName(), user.getNickName());

        // 设置部落的创建时间
        insertTribe.setCreateTime(LocalDateTime.now());

        // 插入到数据库中
        int insert = TRIBE_MAPPER.insert(insertTribe);
        if (insert != 1) {
            throw new ServiceException("创建部落功能异常！");
        }

        // 更新用户的金币信息，部落id信息，角色权限信息
        int updateCoins = user.getCoins() - CREATE_COINS;
        user.setCoins(updateCoins);
        user.setTribeId(id);
        user.setRoleId(5);
        int update = USER_MAPPER.update(user);
        if (update != 1) {
            throw new ServiceException("创建部落功能异常！");
        }

        Apply apply = APPLY_MAPPER.selectOneByFields(new Apply(user.getId()));
        if (apply != null) {
            int delete = APPLY_MAPPER.delete(new Apply(user.getId()));
            if (delete != 1) {
                throw new ServiceException("创建部落功能异常！");
            }
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }

    @Override
    public ResultInfo<List<Tribe>> selectAllCampTribeList(int campId, int count) {
        // 查询当前阵营的所有部落
        List<Tribe> tribes = TRIBE_MAPPER.selectAllCampTribeList(campId, count);
        // 判断当前页码不为0且集合的大小为0，返回空集合
        if (tribes.size() == 0 && count == 0) {
            return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(), tribes);
        }
        if (tribes.size() == 0) {
            return ResultInfo.operateRejectWithMessage("这是尾页！");
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(), tribes);
    }

    @Override
    public ResultInfo<List<Tribe>> selectSearchTribeList(int campId, String tribeName, int pageCount) {
        // 通过阵营和部落模糊名，页码查询部落列表
        List<Tribe> tribes = TRIBE_MAPPER.selectSearchTribeList(campId, tribeName, pageCount);
        // 判断集合大小和页码，返回拒绝信息
        if (tribes.size() == 0 && pageCount == 0) {
            String tribeActualName = tribeName.replaceAll("%", "");
            return ResultInfo.operateRejectWithMessage("抱歉没有找到与" + tribeActualName + "有关的部落名");
        }
        // 判断集合大小，返回拒绝信息
        if (tribes.size() == 0) {
            return ResultInfo.operateRejectWithMessage("这是尾页！");
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(), tribes);
    }

    @Override
    public ResultInfo<Tribe> selectTribeByTribeId(String tribeId) {
        // 通过部落id获得当前部落
        Tribe tribe = new Tribe();
        tribe.setId(tribeId);
        tribe = TRIBE_MAPPER.selectById(tribe);
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(), tribe);
    }


    @Override
    public ResultInfo<List<User>> selectUserListByGenderAndTribeId(String tribeId, String searchName, String gender, int pageCount) {
        List<User> users = null;
        // 判断模糊名和性别同时为空
        if (ValidateUtil.strIsNullOrEmpty(searchName) && gender == null) {
            users = USER_MAPPER.selectUserListByTribeId(tribeId, pageCount);
        }
        // 判断模糊名不为空，性别为空
        if (!ValidateUtil.strIsNullOrEmpty(searchName) && gender == null) {
            users = USER_MAPPER.selectUserListByTribeIdAndSearchName(tribeId, searchName, pageCount);
        }
        // 判断模糊名不为空，性别不为空
        if (ValidateUtil.strIsNullOrEmpty(searchName) && gender != null) {
            users = USER_MAPPER.selectUserListByGenderByTribeId(tribeId, gender, pageCount);
        }
        // 判断模糊名和性别同时不为空
        if (!ValidateUtil.strIsNullOrEmpty(searchName) && gender != null) {
            users = USER_MAPPER.selectUserListByGenderAndTribeIdAndSearchName(tribeId, gender, searchName, pageCount);
        }
        // 判断用户集合不为空且集合大小大于0，返回空集合
        if (users != null && users.size() > 0) {
            return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(), users);
        }
        // 判断性别和模糊名不为空且页码为0时，返回选择性别时的拒绝信息
        if (gender != null && !ValidateUtil.strIsNullOrEmpty(searchName) && pageCount == 0) {
            String tribeActualName = searchName.replaceAll("%", "");
            return ResultInfo.operateRejectWithMessage("抱歉没有找到与" + tribeActualName + "有关的" + gender + "性用户!");
        }
        // 判断模糊名不为空且页码为0时，返回不选择性别时的拒绝信息
        if (!ValidateUtil.strIsNullOrEmpty(searchName) && pageCount == 0) {
            String tribeActualName = searchName.replaceAll("%", "");
            return ResultInfo.operateRejectWithMessage("抱歉没有找到与" + tribeActualName + "有关的用户!");
        }
        // 判断性别为空且页码为0时，返回没有这一性别的用户拒绝信息
        if (gender != null && pageCount == 0) {
            return ResultInfo.operateRejectWithMessage("本部落没有" + gender + "性用户!");
        }
        return ResultInfo.operateRejectWithMessage("这是尾页！");
    }


    @Override
    public ResultInfo<String> kickTribe(User user, String chooseName) {
        // 判断当前用户昵称和选择的昵称是否一致，返回拒绝信息
        if (user.getNickName().equals(chooseName)) {
            return ResultInfo.operateRejectWithMessage("下面有退出部落按钮，别在这瞎搞！");
        }

        // 获取被选择用户的信息
        User chooseUser = new User();
        chooseUser.setNickName(chooseName);
        chooseUser = USER_MAPPER.selectOneByFields(chooseUser);

        // 判断当前用户角色权限是否小于被选择用户的角色权限，返回拒绝信息
        if (chooseUser.getRoleId() > user.getRoleId()) {
            return ResultInfo.operateRejectWithMessage("反了你？想把首领踢出部落？");
        }

        // 判断当前用户角色权限是否等于被选择用户的角色权限，返回拒绝信息
        if (chooseUser.getRoleId().equals(user.getRoleId())) {
            return ResultInfo.operateRejectWithMessage("你怎么能把自己同等权限的人踢出去呢？");
        }

        // 更改被选择用户部落id，角色权限，退出部落时间
        chooseUser.setTribeId("");
        chooseUser.setRoleId(SCAVENGER_ID);
        chooseUser.setExitTribeDate(LocalDateTime.now());
        int update = USER_MAPPER.update(chooseUser);
        if (update != 1) {
            throw new ServiceException("踢出部落功能异常！");
        }

        // 获取该用户的申请id和部落id
        Apply apply = new Apply();
        apply.setApplicantId(chooseUser.getId());
        apply.setApplyingTribeId(user.getTribeId());
        List<Apply> applies = APPLY_MAPPER.selectListByFields(apply);

        // 判断申请中是否有过去部落申请通过的审核内容，将其删除
        if (applies != null && applies.size() > 0) {
            int delete = APPLY_MAPPER.delete(apply);
            if (delete != applies.size()) {
                throw new ServiceException("踢出部落功能异常！");
            }
        }
        // 为被选择用户创建部落去留踢出部落通知
        NoticeServiceImpl.setNoticeForUser(chooseUser, "部落去留", "尊敬的" + chooseName
                + "用户，您已被踢出部落");
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());

    }

    @Override
    public ResultInfo<Long> selectNumbersForTribe(String tribeId) {
        // 通过部落id获取当前部落人数
        Long numbers = USER_MAPPER.selectNumbersForTribe(tribeId);
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(), numbers);
    }

    @Override
    public ResultInfo<String> exitTribe(User user) {

        // 判断当前用户的角色权限是否为首领，返回拒绝信息
        if (user.getRoleId() == LEADER_ID) {
            return ResultInfo.operateRejectWithMessage("你要先转让你的首领职位！");
        }

        // 更改当前用户部落id为空，角色权限，退出部落时间
        String tribeId = user.getTribeId();
        user.setRoleId(1);
        user.setTribeId("");
        user.setExitTribeDate(LocalDateTime.now());
        int update = USER_MAPPER.update(user);
        if (update != 1) {
            throw new ServiceException("推出部落功能异常！");
        }

        // 通过部落id获取部落
        Tribe tribe = new Tribe();
        tribe.setId(tribeId);
        tribe = TRIBE_MAPPER.selectById(tribe);

        // 获取部落的首领信息
        User leaderUser = new User();
        leaderUser.setNickName(tribe.getCurrentLeader());
        leaderUser = USER_MAPPER.selectOneByFields(leaderUser);

        // 为部落首领创建部落成员退出的通知
        NoticeServiceImpl.setNoticeForUser(leaderUser, "部落去留", "用户" + user.getNickName() + "已退出部落");
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }

    @Override
    public ResultInfo<String> coinToCoins(User user, int coinToCoins) {
        // 更新用户的金币数量
        user.setCoins(user.getCoins() - coinToCoins);
        int update = USER_MAPPER.update(user);
        if (update != 1) {
            throw new ServiceException("贡献金币功能异常！");
        }

        // 更新部落的金币数量
        Tribe tribe = new Tribe();
        tribe.setId(user.getTribeId());
        tribe = TRIBE_MAPPER.selectById(tribe);
        tribe.setCoins(tribe.getCoins() + coinToCoins);
        int update1 = TRIBE_MAPPER.update(tribe);
        if (update1 != 1) {
            throw new ServiceException("贡献金币功能异常！");
        }

        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }

    @Override
    public ResultInfo<String> coinToPower(Tribe tribe, int coinToPower) {
        // 更新部落的金币和战力
        // 10 金币 等于 1 战力
        tribe.setCoins(tribe.getCoins() - coinToPower);
        tribe.setCombatPower(tribe.getCombatPower() + coinToPower / 10);
        int update = TRIBE_MAPPER.update(tribe);
        if (update != 1) {
            throw new ServiceException("交换金币功能异常！");
        }

        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }

    @Override
    public ResultInfo<String> levelUp(Tribe tribe) {
        // 更新部落等级和金币
        tribe.setTribeLevel(tribe.getTribeLevel() + 1);
        tribe.setCoins(tribe.getCoins() - LEVEL_COINS);
        int update = TRIBE_MAPPER.update(tribe);
        if (update != 1) {
            throw new ServiceException("部落升级功能异常！");
        }

        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());

    }

    @Override
    @Transaction
    public ResultInfo<String> dismissTribe(String tribeId) {
        // 获取当前部落信息，删除当前部落
        Tribe tribe = new Tribe();
        tribe.setId(tribeId);
        tribe = TRIBE_MAPPER.selectById(tribe);
        int delete = TRIBE_MAPPER.delete(tribe);
        if (delete != 1) {
            throw new ServiceException("解散部落功能异常！");
        }

        // 通过被删除的部落的id获取该部落的用户集合
        User selectUser = new User();
        selectUser.setTribeId(tribeId);
        List<User> users = USER_MAPPER.selectListByFields(selectUser);

        // 遍历users，更新用户部落，用户权限，用户金币，退出部落时间
        for (User user : users) {
            user.setTribeId("");
            user.setRoleId(SCAVENGER_ID);
            user.setCoins(user.getCoins() + tribe.getCoins() / users.size());
            user.setExitTribeDate(LocalDateTime.now());
            int update = USER_MAPPER.update(user);
            if (update != 1) {
                throw new ServiceException("解散部落功能异常！");
            }
            NoticeServiceImpl.setNoticeForUser(user, "部落通知", "您所在的部落已被解散！");
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }

    @Override
    @Transaction
    public ResultInfo<String> tribeSignIn(User user) {
        // 判断当前用户是否拥有部落签到数据
        if (user.getTribeSignDate() == null) {
            // 设置昨天的日期
            user.setTribeSignDate(SecurityUtil.yesterdayDateTime());
            int update = USER_MAPPER.update(user);
            if (update != 1) {
                throw new ServiceException("部落签到功能异常！");
            }
            user = USER_MAPPER.selectById(new User(user.getId()));
        }

        // 判断签到时间是否超过一天
        if (SecurityUtil.isLessThanOneDay(user.getTribeSignDate())) {
            return ResultInfo.operateRejectWithMessage("请明天再来签到吧！");
        }

        // 随机增加的金币和战力
        Random random = new Random();
        // 50-100金币
        int addCoins = random.nextInt(51) + 50;
        // 100-200战力
        int addPower = random.nextInt(101) + 100;

        // 更新部落信息
        Tribe tribe = new Tribe();
        tribe.setId(user.getTribeId());
        tribe = TRIBE_MAPPER.selectById(tribe);
        tribe.setCoins(tribe.getCoins() + addCoins);
        tribe.setCombatPower(tribe.getCombatPower() + addPower);
        int update = TRIBE_MAPPER.update(tribe);
        if (update != 1) {
            throw new ServiceException("部落签到功能异常！");
        }
        user.setTribeSignDate(LocalDateTime.now());
        USER_MAPPER.update(user);

        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());

    }

    @Override
    public ResultInfo<String> permissionGive(User user, String chooseName, int roleId) {
        // 判断是否对自己进行操作
        if (user.getNickName().equals(chooseName)) {
            return ResultInfo.operateRejectWithMessage("对自己动手动脚的做什么！");
        }
        // 如果自己是副首领，不能将他人权限提升至副首领
        if (user.getRoleId() == DEPUTY_CHIEF_ID && roleId == DEPUTY_CHIEF_ID) {
            return ResultInfo.operateRejectWithMessage("你怎么能提携他呢？");
        }

        // 通过用户昵称来获得被选择的用户对象
        User chooseUser = new User();
        chooseUser.setNickName(chooseName);
        chooseUser = USER_MAPPER.selectOneByFields(chooseUser);

        // 如果自己是首领，要将首领交给选择的人，自己的身份变更为副首领
        if (roleId == LEADER_ID) {

            // 更改被选择用户的角色权限
            chooseUser.setRoleId(roleId);
            int update = USER_MAPPER.update(chooseUser);
            if (update != 1) {
                throw new ServiceException("部落授权功能异常！");
            }

            // 更改当前用户的角色权限
            user.setRoleId(DEPUTY_CHIEF_ID);
            int update1 = USER_MAPPER.update(user);
            if (update1 != 1) {
                throw new ServiceException("部落授权功能异常！");
            }
            // 通过部落id来获取当前部落
            Tribe tribe = new Tribe();
            tribe.setId(user.getTribeId());
            tribe = TRIBE_MAPPER.selectOneByFields(tribe);

            // 更改部落当前首领名
            tribe.setCurrentLeader(chooseName);
            int update2 = TRIBE_MAPPER.update(tribe);
            if (update2 != 1) {
                throw new ServiceException("部落授权功能异常！");
            }
            NoticeServiceImpl.setNoticeForUser(chooseUser, "权限变更", "您已被升级为首领！");
            return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
        }

        // 查询被选择用户的当前用户的角色权限
        int beforeRoleId = chooseUser.getRoleId();

        // 如果被选择的用户角色权限等于更改的角色权限
        if (chooseUser.getRoleId() == roleId) {
            return ResultInfo.operateRejectWithMessage("这操作我看着很迷！");
        }

        // 更改被选择用户的权限
        chooseUser.setRoleId(roleId);
        int update = USER_MAPPER.update(chooseUser);
        if (update != 1) {
            throw new ServiceException("部落授权功能异常！");
        }

        // 对被选择用户通知升级或降级
        Role role = new Role();
        role.setId(roleId);
        role = ROLE_MAPPER.selectById(role);
        if (beforeRoleId > roleId) {
            NoticeServiceImpl.setNoticeForUser(chooseUser, "权限变更", "您已被降级为" + role.getRoleName());
        } else {
            NoticeServiceImpl.setNoticeForUser(chooseUser, "权限变更", "您已被升级为" + role.getRoleName());
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }
}
